package com.gitee.smsdistribution.service;


import com.gitee.smsdistribution.common_response.exception.SendSmsException;
import com.gitee.smsdistribution.model.DistributionPolicy;
import com.gitee.smsdistribution.model.SendState;
import com.gitee.smsdistribution.model.SendWay;
import com.gitee.smsdistribution.model.SmsInfo;
import com.gitee.smsdistribution.model.Strategy;
import com.gitee.smsdistribution.repository.SmsInfoRepository;
import com.gitee.smsdistribution.strategy.impl.ByCompanyGenUniqueLinkStrategy;
import com.gitee.smsdistribution.util.Constant;
import com.gitee.smsdistribution.util.SendUtils;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@Service
public class SmsInfoService {

    private final SmsInfoRepository smsInfoRepository;
    private final DistributionPolicyService distributionPolicyService;
    private final SendUtils sendUtils;

    @Value("${send-way.way-1}")
    private String way1;

    /**
     * 群发
     *
     * @param ids
     * @param sendWay
     */
    public void sendSms(List<Long> ids, SendWay sendWay) throws Exception {
        List<SmsInfo> smsInfos = smsInfoRepository.findAllById(ids);
        Date now = new Date();

        for (SmsInfo smsInfo : smsInfos) {

            if (SendState.SENT.equals(smsInfo.getSendState())) {
                continue;
            }

            // 获取唯一链接
            DistributionPolicy distributionPolicy = distributionPolicyService.findByName(smsInfo.getTemplateName());
            String uniqueLink = Constant.EMPTY;
            Strategy strategy = distributionPolicy.getStrategy();
            switch (strategy) {
                case BY_COMPANY_GEN_UNIQUE_LINK -> {
                    ByCompanyGenUniqueLinkStrategy uniqueLinkStrategy = new ByCompanyGenUniqueLinkStrategy(smsInfo, distributionPolicy);
                    uniqueLink = uniqueLinkStrategy.generateUniqueLink();
                }
                default -> {
                }
            }

            // 生成短信内容
            String content = Constant.EMPTY;
            switch (sendWay) {
                case WAY_1 -> {
                    content = fillParam(way1, smsInfo.getCompany(), uniqueLink);
                }
                default -> {
                }
            }

            int statusCode = sendUtils.sendSms(smsInfo.getPhone(), content);
            if (statusCode != 200) {
                throw new SendSmsException(smsInfo.getCompany() + " 公司短信发送失败", Map.of("短信发送失败状态码", statusCode));
            }

            smsInfo.setSendState(SendState.SENT)
                    .setSendDate(now);
            smsInfoRepository.save(smsInfo);
        }
    }

    private String fillParam(String sendWay, Object... params) {
        for (Object param : params) {
            sendWay = sendWay.replaceFirst("\\{}", param.toString());
        }

        return sendWay;
    }

    /**
     * 新增群发公司记录
     *
     * @param smsInfos
     */
    public List<SmsInfo> addSmsInfo(List<SmsInfo> smsInfos) {
        return smsInfoRepository.saveAll(smsInfos);
    }

    /**
     * 分页列表
     *
     * @param keyword 可以根据公司名、联系人、手机号查找、关联模板
     */
    public Page<SmsInfo> pageList(String keyword, Date startDate, Date endDate, int pageNumber, int pageSize) {
        // 创建分页对象
        Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(Sort.Direction.DESC, "id"));
        return smsInfoRepository.searchByKeyword(keyword, startDate, endDate, pageable);
    }
}
